﻿using Events.Dto;
using Filters;
using Furion.DataEncryption;
using Furion.EventBus;

namespace Services.Client;

/// <summary>
/// 用户
/// </summary>
[Authorize, ApiDescriptionSettings("客户")]
public class ClientServices : BaseServices
{
    private readonly ISqlSugarClient db;


    private readonly IEventPublisher pub;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="db"></param>
    /// <param name="ali"></param>
    /// <param name="douyin"></param>
    public ClientServices(ISqlSugarClient db, IEventPublisher pub)
    {
        this.db = db;
        this.pub = pub;
    }



    /// <summary>
    /// mock
    /// </summary>
    /// <param name="id"></param>
    /// <param name="pwd"></param>
    /// <returns></returns>
    [AllowAnonymous]
    public async Task<object> Mock(int id, string pwd)
    {
        if (pwd != "Bhkloo8o2e.") return No("pwd error");

        var user = await db.Queryable<Entity.Client>().FirstAsync(x => x.Id == id);


        var token = JWTEncryption.Encrypt(new Dictionary<string, object>
        {
            { "UserId", user.Id },

            { "Role", Enums.TokenRole.客户 }
        });

        return Ok(new { token });
    }

    /// <summary>
    /// 设置用户信息
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public async Task<object> SetUserInfo(Dto.SetUserInfoDto e)
    {
        var user = await db.Queryable<Entity.Client>().FirstAsync(x => x.Id == USERID);

        if (user == null) return No("账户不存在");

        user.Avatar = e.Avatar;

        user.Name = e.NickName;

        user.BindUserInfo = true;

        bool state = await db.Updateable(user).ExecuteCommandHasChangeAsync();

        return Msg(state);
    }

    /// <summary>
    /// 获取资金记录
    /// </summary>
    /// <param name="state"></param>
    /// <returns></returns>
    public async Task<object> GetMoneyLog(int state)
    {
        var log = await db.Queryable<Entity.ClientMoneyLog>()

            .Where(x => x.UID == USERID)

            .WhereIF(state > -1, x => x.ChangeType == state)

            .ToPagedListAsync(PageNo, PageSize);

        return Ok(log);
    }

    /// <summary>
    /// 详情
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetDetail()
    {
        return Ok(await db.Queryable<Entity.Client>().FirstAsync(x => x.Id == USERID));
    }

    /// <summary>
    /// 检测是否绑定信息
    /// </summary>
    /// <returns></returns>
    public async Task<object> CheckUserInfoBind()
    {
        var info = await db.Queryable<Entity.Client>()

            .Where(x => x.Id == USERID)

            .Select<dynamic>(x => new { x.BindPhone, x.BindUserInfo })

            .FirstAsync();


        return Ok(info);
    }

    /// <summary>
    /// 绑定手机号
    /// </summary>
    /// <param name="phone"></param>
    /// <param name="code"></param>
    /// <returns></returns>
    [PhoneCode]
    public async Task<object> BindPhone([FromQuery] string phone)
    {
        var client = await db.Queryable<Entity.Client>().FirstAsync(x => x.Id == USERID);

        if (client == null) return No("账户不存在!");

        client.Phone = phone;

        client.BindPhone = true;

        bool state = await db.Updateable(client).ExecuteCommandHasChangeAsync();

        return Ok(state);
    }

    /// <summary>
    /// 获取用户积分
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetPoint()
    {
        var data = await db.Queryable<Entity.ClientPoints>()

            .Where(x => x.ClientId == USERID)

            .FirstAsync();

        return Ok(data);
    }

    /// <summary>
    /// 获取积分 余额 金币
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetMoney()
    {
        var client = await db.Queryable<Entity.Client>().FirstAsync(x => x.Id == USERID);

        var point = await db.Queryable<Entity.ClientPoints>().Where(x => x.ClientId == USERID).Select(x=>x.Points).FirstAsync();

        var glod = await db.Queryable<Entity.ClientGlod>().Where(x => x.ClientId == USERID).Select(x => x.Glod).FirstAsync();

        return Ok(new 
        {
            money = client.Money,

            point = point,

            glod = glod,
        });
    }

    /// <summary>
    /// 获取积分记录
    /// </summary>
    /// <param name="type"> -1 全部 0支出  1收入</param>
    /// <returns></returns>
    public async Task<object> GetPointLog(int type)
    {
        var log = await db.Queryable<Entity.ClientPointsLog>()

            .WhereIF(type > -1, x => x.UsedType == type)

            .Where(x => x.ClientId == USERID)

            .ToPagedListAsync(PageNo, PageSize);

        return Ok(log);
    }

    /// <summary>
    /// 获取金币记录
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<object> GetGlodLog(int type)
    {
        var list = await db.Queryable<Entity.ClientGlodLog>()

            .Where(x => x.ClientId == USERID)

            .WhereIF(type > -1, x => x.UsedType == type)

            .ToPagedListAsync(PageNo, PageSize);

        return Ok(list);
    }

    /// <summary>
    /// 用户签到
    /// </summary>
    /// <returns></returns>
    public async Task<object> Signin()
    {
        //签到送的积分数
        decimal sendPoints = 100;

        var toDay = await db.Queryable<Entity.SignLog>().Where(x => x.ClientId == USERID && x.Created.ToString("yyyyMMdd") == DateTime.Now.ToString("yyyyMMdd")).FirstAsync();

        if (toDay != null) return No("今日已签到");

        var yearToDay = await db.Queryable<Entity.SignLog>().Where(x => x.ClientId == USERID && x.Created.ToString("yyyyMMdd") == DateTime.Now.AddDays(-1).ToString("yyyyMMdd")).FirstAsync();

        //连续签到天数
        int consecutive_days = 1;

        if (yearToDay != null) consecutive_days = yearToDay.consecutive_days + 1;

        var data = new Entity.SignLog
        {
            consecutive_days = consecutive_days,

            ClientId = USERID,

            Points = sendPoints
        };

        bool state = await db.Insertable(data).ExecuteCommandAsync() > 0;

        if (state)
        {
            await pub.PublishAsync("sendPoint", new SendPoint
            {
                memo = "签到积分",

                Point = sendPoints,

                UserId = USERID
            });
        }

        return Msg(state);
    }

    /// <summary>
    /// 签到记录
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetSignLog()
    {
        var data = await db.Queryable<Entity.SignLog>()

            .Where(x => x.ClientId == USERID)

            .Where(x => x.Created.ToString("yyyyMM") == DateTime.Now.ToString("yyyyMM"))

            .ToListAsync();

        return Ok(data);
    }

    /// <summary>
    /// 连续签到规则
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetSignrule()
    {
        var data = await db.Queryable<Entity.SignRule>().ToListAsync();

        return Ok(data);
    }

    /// <summary>
    /// 获取门店信息
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<object> GetStoreInfo(int id)
    {
        var data = await db.Queryable<Entity.Store>().FirstAsync(x => x.Id == id);

        return Ok(new { name = data.Name, avatar = data.Avatar });
    }
}
